package com.myschool.server.interceptor;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class DateInterceptor extends EmptyInterceptor {
	/** Constant serial version ID. */
	private static final long serialVersionUID = 8351540595499277826L;

	/** The name of the created field in BaseEntity. */
	private static final String CREATED_FIELD = "createdDate";

	/** The name of the modified field in BaseEntity. */
	private static final String MODIFIED_FIELD = "lastUpdatedDate";

	/**
	 * When an entity is saved (inserted), ensure that the created property is
	 * set with the current date.
	 * 
	 * @param entity
	 *            The entity being saved.
	 * @param entityId
	 *            The ID of the entity.
	 * @param state
	 *            The state of the entity (an array element for each property).
	 * @param propertyNames
	 *            The names of each property in the entity.
	 * @param types
	 *            The types of each property in the entity.
	 * 
	 * @return True if a change was made, false otherwise.
	 */
	@Override
	public boolean onSave(final Object entity, final Serializable entityId,
			final Object[] state, final String[] propertyNames,
			final Type[] types) {
		for (int i = 0; i < propertyNames.length; i++) {
			if (MODIFIED_FIELD.equals(propertyNames[i])) {
				state[i] = new Date();
				return true;
			}
		}

		return false;
	}

	/**
	 * When an entity is updated, ensure that the modified property is set with
	 * the current date.
	 * 
	 * @param entity
	 *            The entity being updated.
	 * @param entityId
	 *            The ID of the entity being updated.
	 * @param currentState
	 *            The state that will be saved (an array element for each
	 *            property).
	 * @param previousState
	 *            The state before the update.
	 * @param propertyNames
	 *            The name of each property in the entity.
	 * @param types
	 *            The type of each property.
	 * 
	 * @return True if a change is made, false otherwise.
	 */
	@Override
	public boolean onFlushDirty(final Object entity,
			final Serializable entityId, final Object[] currentState,
			final Object[] previousState, final String[] propertyNames,
			final Type[] types) {
		for (int i = 0; i < propertyNames.length; i++) {
			if (MODIFIED_FIELD.equals(propertyNames[i])) {
				currentState[i] = new Date();
				return true;
			}
		}

		return false;
	}
}
